<template>
  <v-app class="note-timeline-app">
    <v-container class="pa-0 h-100" fluid>
      <!-- 左侧筛选抽屉：仅类型 + 关键字 -->
      <v-navigation-drawer
        v-model="drawerOpen"
        app
        location="left"
        :permanent="!xs"
        :temporary="xs"
        width="230"
      >
        <v-sheet class="pa-3 pb-1">
          <v-autocomplete
            v-model="contactSelectModel"
            clearable
            density="compact"
            hide-details
            item-title="name"
            item-value="id"
            :items="contactOptions"
            :label="t('sidebar.contact')"
            variant="outlined"
          />
        </v-sheet>
        <v-sheet class="px-3 pt-2">
          <v-text-field
            v-model="keywordInput"
            clearable
            density="compact"
            hide-details
            :label="t('sidebar.keyword')"
            variant="outlined"
            @click:clear="clearKeyword"
            @keyup.enter="applyKeyword"
          />
        </v-sheet>
        <v-sheet class="px-3 pt-3">
          <VDateInput
            v-model="dateRangeValue"
            clearable
            density="compact"
            hide-details
            :label="t('sidebar.sectionDateRange')"
            multiple="range"
            prepend-icon=""
          />
        </v-sheet>
        <v-divider class="my-2" />

        <v-list density="default">
          <v-list-item :active="!filters.type" @click="clearType()">
            <template #prepend>
              <v-avatar color="primary" size="24" variant="flat">
                <v-icon color="white" :icon="mdiSelectAll" size="16" />
              </v-avatar>
            </template>
            <v-list-item-title>{{ t('sidebar.all') }}</v-list-item-title>
            <template #append>
              <v-chip color="primary" size="x-small" variant="tonal">{{ totalCount }}</v-chip>
            </template>
          </v-list-item>

          <v-list-subheader>{{ t('type.label') }}</v-list-subheader>
          <v-list-item
            v-for="item in typeCounts"
            :key="item.type"
            :active="filters.type === item.type"
            @click="selectType(item.type)"
          >
            <template #prepend>
              <v-avatar :color="brandColorForType(item.type) || 'primary'" size="24" variant="flat">
                <v-icon color="white" :icon="iconForType(item.type)" size="16" />
              </v-avatar>
            </template>
            <v-list-item-title>{{ typeLabel(item.type) }}</v-list-item-title>
            <template #append>
              <v-chip color="primary" size="x-small" variant="tonal">{{ item.count }}</v-chip>
            </template>
          </v-list-item>
        </v-list>
      </v-navigation-drawer>

      <v-app-bar v-if="xs" app density="compact" flat>
        <v-btn icon variant="text" @click="drawerOpen = true">
          <v-icon :icon="mdiMenu" />
        </v-btn>
        <v-toolbar-title class="text-subtitle-1">{{ t('title') }}</v-toolbar-title>
      </v-app-bar>

      <!-- 主内容区 -->
      <v-main>
        <v-container class="py-4 px-6" :class="containerClass">
          <v-row justify="center">
            <v-col cols="12" :lg="8" :md="10" :sm="12">
              <!-- 创建笔记输入框（已提取为可复用组件） -->
              <NoteComposer
                ref="noteComposerRef"
                :create-note="noteService.createNote"
                @submitted="handleComposerSubmitted"
              />

              <!-- 加载状态 -->
              <div v-if="loading" class="text-center py-8">
                <v-progress-circular color="primary" indeterminate size="64" />
                <p class="text-body-1 mt-4 text-medium-emphasis">{{ t('loading') }}</p>
              </div>

              <!-- 空状态 -->
              <div v-else-if="notes.length === 0" class="text-center py-12">
                <v-icon color="grey-lighten-1" :icon="mdiNoteTextOutline" size="80" />
                <p class="text-h6 mt-4 text-medium-emphasis">{{ t('emptyState') }}</p>
                <p class="text-body-2 text-medium-emphasis">
                  {{ t('emptyStateHint') }}
                </p>
                <v-btn
                  class="mt-4"
                  color="primary"
                  :prepend-icon="mdiPlus"
                  variant="elevated"
                  @click="focusComposer"
                >
                  {{ t('createFirstNote') }}
                </v-btn>
              </div>

              <!-- 笔记列表 -->
              <div v-else>
                <!-- 笔记列表（按类型/关键字服务端筛选） -->
                <NoteCard
                  v-for="note in notes"
                  :key="note.id"
                  :note="note"
                  @delete="handleDelete"
                  @edit="handleEdit"
                />

                <!-- 加载更多 -->
                <div v-if="hasMore" class="text-center py-4">
                  <v-btn
                    color="primary"
                    :loading="loadingMore"
                    variant="outlined"
                    @click="loadMore"
                  >
                    {{ t('loadMore') }}
                  </v-btn>
                </div>
              </div>
            </v-col>
          </v-row>
        </v-container>
      </v-main>

      <!-- 新建/编辑笔记对话框 -->
      <NoteDialog
        v-model="showCreateDialog"
        :note="editingNote"
        @close="handleCloseDialog"
        @save="handleSave"
      />
    </v-container>
  </v-app>
</template>

<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useDisplay } from 'vuetify'
import { mdiMenu, mdiNoteTextOutline, mdiPlus, mdiSelectAll } from '@mdi/js'
import { getBrandColorByType, getIconByType } from './icons'
import { useSystemStateListener } from '@/composables/useSystemStateListener'
import NoteCard from './components/NoteCard.vue'
import NoteDialog from './components/NoteDialog.vue'
import NoteComposer from './components/NoteComposer.vue'

import type { Note, QueryNoteParams } from './types'
import { noteService } from './services/noteService'

import { VDateInput } from 'vuetify/labs/VDateInput'

const { t } = useI18n()

// 启动系统状态监听器
useSystemStateListener()

function iconForType(type: Note['type']) {
  return type === 'note' ? mdiNoteTextOutline : getIconByType(type)
}

function brandColorForType(type: Note['type']) {
  return getBrandColorByType(type)
}

function typeLabel(type: Note['type']) {
  const key = `type.${type}`
  const label = t(key)
  return label || type
}

async function loadTypeCounts() {
  const { keyword, created_at_from, created_at_to, contact_id } = filters.value
  typeCounts.value = await noteService.getTypeCounts({
    keyword,
    created_at_from,
    created_at_to,
    contact_id
  })
}

function selectType(type: Note['type']) {
  filters.value.type = type
  filters.value.category = undefined
  filters.value.offset = 0
  loadNotes()
  loadTypeCounts()
  loadContacts()
}

const { smAndDown, xs } = useDisplay()

// 响应式布局
const containerClass = computed(() => (smAndDown.value ? 'px-2' : 'px-4'))

// 状态管理
// 联系人筛选（左侧 v-autocomplete）
const contactOptions = ref<Array<{ id: number; name: string }>>([])

const contactSelectModel = computed<number | null>({
  get: () => filters.value.contact_id ?? null,
  set: (val: number | null) => onContactChange(val)
})

async function loadContacts() {
  const { keyword, created_at_from, created_at_to, type } = filters.value
  contactOptions.value = await noteService.listContacts({
    keyword,
    created_at_from,
    created_at_to,
    type
  })
}

function onContactChange(val: number | null) {
  filters.value.contact_id = val ?? undefined
  // 变更联系人时，将类型重置为“全部”
  clearType()
}

const notes = ref<Note[]>([])
const typeCounts = ref<Array<{ type: Note['type']; count: number }>>([])
const totalCount = computed(() => typeCounts.value.reduce((s, x) => s + x.count, 0))
const loading = ref(false)
function clearType() {
  filters.value.type = undefined
  // 兼容旧逻辑：彻底清空类别
  // @ts-ignore
  filters.value.category = undefined
  filters.value.offset = 0
  loadNotes()
  loadTypeCounts()
  loadContacts()
}

const loadingMore = ref(false)
const hasMore = ref(true)
const showCreateDialog = ref(false)
const editingNote = ref<Note | null>(null)

// 顶部内联输入（已提取为 NoteComposer）
const noteComposerRef = ref<any>(null)
watch(xs, isXs => {
  if (isXs) drawerOpen.value = false
})

function startOfDay(d: Date): number {
  const x = new Date(d)
  x.setHours(0, 0, 0, 0)
  return x.getTime()
}
function endOfDay(d: Date): number {
  const x = new Date(d)
  x.setHours(23, 59, 59, 999)
  return x.getTime()
}

function setCreatedRange(from?: number, to?: number) {
  if (from === undefined) {
    delete filters.value.created_at_from
  } else {
    filters.value.created_at_from = from
  }
  if (to === undefined) {
    delete filters.value.created_at_to
  } else {
    filters.value.created_at_to = to
  }
}

// 左侧筛选抽屉（类型 + 关键字）
const drawerOpen = ref(!xs.value)
const keywordInput = ref<string>('')

function applyKeyword() {
  const kw = keywordInput.value.trim()
  filters.value.keyword = kw ? kw : undefined
  // 变更关键字：重置类型为“全部”，但不刷新联系人候选
  filters.value.type = undefined
  // @ts-ignore
  filters.value.category = undefined
  filters.value.offset = 0
  loadNotes()
  loadTypeCounts()
}

function clearKeyword() {
  keywordInput.value = ''
  applyKeyword()
}

const filters = ref<QueryNoteParams>({
  limit: 20,
  offset: 0,
  order_by: 'created_at',
  order_direction: 'desc'
})

// 日期范围（使用 Vuetify v-date-input 的 range 模式）
const dateRangeValue = ref<any>(null)
watch(dateRangeValue, val => {
  let start: Date | undefined
  let end: Date | undefined
  if (Array.isArray(val)) {
    start = val[0] ?? undefined
    end = val[1] ?? undefined
  } else if (val && typeof val === 'object') {
    // 兼容不同返回结构
    start = (val.start ?? val.from) as Date | undefined
    end = (val.end ?? val.to) as Date | undefined
  } else if (val instanceof Date) {
    start = val
    end = val
  }
  if (start && (!end || end.getTime() < start.getTime())) {
    const tmp = new Date(start)
    tmp.setDate(tmp.getDate() + 1)
    end = tmp
  }
  const fromTs = start ? startOfDay(start) : undefined
  const toTs = end ? endOfDay(end) : undefined
  setCreatedRange(fromTs, toTs)
  // 变更日期范围：重置类型为“全部”，但不刷新联系人候选
  filters.value.type = undefined
  // 兼容旧逻辑：彻底清空类别
  // @ts-ignore
  filters.value.category = undefined
  filters.value.offset = 0
  loadNotes()
  loadTypeCounts()
})

// 加载笔记列表
async function loadNotes(append = false) {
  try {
    if (append) {
      loadingMore.value = true
    } else {
      loading.value = true
    }

    // 使用 noteService 获取数据
    const data = await noteService.queryNotes(filters.value)

    if (append) {
      notes.value.push(...data)
    } else {
      notes.value = data
    }

    hasMore.value = data.length === filters.value.limit
  } catch (error) {
    console.error('加载笔记失败:', error)
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
function loadMore() {
  const { offset = 0, limit = 20 } = filters.value
  filters.value.offset = offset + limit
  loadNotes(true)
}

// 处理保存
async function handleSave(noteData: any) {
  try {
    if (editingNote.value) {
      const updated = await noteService.updateNote({ id: editingNote.value.id, ...noteData })
      if (updated) {
        const index = notes.value.findIndex(n => n.id === editingNote.value!.id)
        if (index !== -1) notes.value[index] = updated
      }
    } else {
      const newNote = await noteService.createNote(noteData)
      notes.value.unshift(newNote)
    }
    handleCloseDialog()
    await loadTypeCounts()
    await loadContacts()
  } catch (error) {
    console.error('保存笔记失败:', error)
  }
}

function handleComposerSubmitted(note: Note) {
  notes.value.unshift(note)
}

function focusComposer() {
  noteComposerRef.value?.focus?.()
}

// 处理编辑
function handleEdit(note: Note) {
  editingNote.value = note
  showCreateDialog.value = true
}

// 处理删除
async function handleDelete(noteId: number) {
  try {
    await noteService.deleteNote(noteId)
    notes.value = notes.value.filter(n => n.id !== noteId)
    await loadTypeCounts()
    await loadContacts()
  } catch (error) {
    console.error('删除笔记失败:', error)
  }
}

// 关闭对话框
function handleCloseDialog() {
  showCreateDialog.value = false
  editingNote.value = null
}

// 生命周期
onMounted(() => {
  loadNotes()
  loadTypeCounts()
  loadContacts()
})
</script>

<i18n>
{
  "zhHans": {
    "title": "活动时间线",
    "whatsOnYourMind": "写点什么...",
    "filter": "筛选",
    "createNote": "添加记录",
    "createFirstNote": "添加第一条记录",
    "editNote": "编辑记录",
    "loading": "加载中...",
    "loadMore": "加载更多",
    "emptyState": "暂无记录",
    "emptyStateHint": "点击输入框开始添加您的第一条记录",

    "edited": "已编辑",
    "justNow": "刚刚",
    "minutesAgo": "{n} 分钟前",
    "hoursAgo": "{n} 小时前",
    "daysAgo": "{n} 天前",
    "post": "发布",
    "cancel": "取消",
    "addImage": "图片",
    "addFile": "文件",
    "addTag": "标签",
    "enterTag": "请输入标签名称",
    "sidebar": {
      "sectionCategory": "类型",
      "sectionDateRange": "时间范围",
      "keyword": "关键字",
      "contact": "联系人",
      "all": "全部"
    },
    "category": {
      "note": "记录",
      "mail": "邮件",
      "calendar": "日历"
    },
    "type": {
      "label": "记录类型",
      "personal": "个人笔记",
      "company": "公司笔记",
      "contact": "联系人笔记",
      "note": "记录",
      "email": "邮件",
      "event": "事件",
      "inperson": "现场",
      "linkedin": "领英",
      "facebook": "Facebook",
      "x": "X",
      "wechat": "微信",
      "phone": "电话",
      "qq": "QQ",
      "skype": "Skype",
      "telegram": "Telegram",
      "icq": "ICQ",
      "whatsapp": "WhatsApp",
      "line": "LINE"
    }
  },
  "en": {
    "title": "Activity Timeline",
    "whatsOnYourMind": "What's on your mind...",
    "filter": "Filter",
    "createNote": "Add Entry",
    "createFirstNote": "Add your first entry",
    "editNote": "Edit Entry",
    "loading": "Loading...",
    "loadMore": "Load More",
    "emptyState": "No Activities",
    "emptyStateHint": "Click the input box to add your first entry",

    "edited": "Edited",
    "justNow": "Just now",
    "minutesAgo": "{n} minutes ago",
    "hoursAgo": "{n} hours ago",
    "daysAgo": "{n} days ago",
    "post": "Post",
    "cancel": "Cancel",
    "addImage": "Image",
    "addFile": "File",
    "addTag": "Tag",
    "enterTag": "Enter tag name",
    "sidebar": {
      "sectionCategory": "Type",
      "sectionDateRange": "Date Range",
      "keyword": "Keyword",
      "contact": "Contact",
      "all": "All"
    },
    "category": {
      "note": "Records",
      "mail": "Mail",
      "calendar": "Calendar"
    },
    "type": {
      "label": "Entry Type",
      "personal": "Personal",
      "company": "Company",
      "contact": "Contact",
      "note": "Note",
      "email": "Email",
      "event": "Event",
      "inperson": "In-person",
      "linkedin": "LinkedIn",
      "facebook": "Facebook",
      "x": "X",
      "wechat": "WeChat",
      "phone": "Phone",
      "qq": "QQ",
      "skype": "Skype",
      "telegram": "Telegram",
      "icq": "ICQ",
      "whatsapp": "WhatsApp",
      "line": "LINE"
    }
  }
}
</i18n>
